// import { ref, onMounted } from 'vue';

// 搜索表单项接口
export interface FormItem {
  type: 'input' | 'select' | 'date';
  label: string;
  prop: string;
  placeholder?: string;
  options?: Array<{ label: string; value: any }>;
  dateType?:
    | 'date'
    | 'daterange'
    | 'week'
    | 'month'
    | 'year'
    | 'datetime'
    | 'datetimerange'
    | 'monthrange';
  startPlaceholder?: string;
  endPlaceholder?: string;
  valueFormat?: string;
  selectClass?: string;
  selectStyle?: Record<string, any>;
}

// 表格列接口
export interface TableColumn {
  prop?: string;
  label: string;
  width?: number;
  minWidth?: number;
  showOverflowTooltip?: boolean;
  slotName?: string;
  type?: 'action';
  actions?: Array<{
    label: string;
    type?: 'primary' | 'success' | 'warning' | 'danger' | 'info';
    size?: 'large' | 'default' | 'small';
    icon?: string;
    disabled?: boolean | ((row: any) => boolean);
    link?: boolean;
    handler?: (row: any, index: number) => void;
  }>;
}

// 分页参数接口
interface PageParams {
  page: number;
  size: number;
}

// API 响应接口
interface ApiResponse {
  data: {
    list: any[];
    total: number;
  };
}

// Hook 配置接口
interface UseDashboardOptions {
  // API 请求函数（必填）
  fetchApi: (params: any) => Promise<ApiResponse>;
  // 搜索表单配置（可选）
  searchItems?: FormItem[];
  // 表格列配置（可选）
  tableColumns?: TableColumn[];
  // 初始页码（可选，默认1）
  initialPage?: number;
  // 初始每页条数（可选，默认10）
  initialPageSize?: number;
  // 是否立即加载数据（可选，默认true）
  immediate?: boolean;
  // 自定义搜索参数处理函数（可选）
  transformSearchParams?: (params: any) => any;
}

export function useDashboard(options: UseDashboardOptions) {
  const {
    fetchApi,
    searchItems: initialSearchItems = [],
    tableColumns: initialTableColumns = [],
    initialPage = 1,
    initialPageSize = 10,
    immediate = true,
    transformSearchParams
  } = options;

  // 表格数据
  const tableData = ref<any[]>([]);
  const loading = ref(false);
  const currentPage = ref(initialPage);
  const pageSize = ref(initialPageSize);
  const total = ref(0);
  const searchParams = ref<any>({});

  // 搜索条件
  const searchItems = ref<FormItem[]>(initialSearchItems);

  // 表格列配置
  const tableColumns = ref<TableColumn[]>(initialTableColumns);

  // 处理搜索
  const handleSearch = (formData: any) => {
    searchParams.value = transformSearchParams ? transformSearchParams(formData) : formData;
    currentPage.value = 1;
    fetchData();
  };

  // 处理重置
  const handleReset = () => {
    searchParams.value = {};
    currentPage.value = 1;
    fetchData();
  };

  // 处理分页变化
  const handlePageChange = ({ page, size }: PageParams) => {
    currentPage.value = page;
    pageSize.value = size;
    fetchData();
  };

  // 获取表格数据
  const fetchData = async (extraParams = {}) => {
    loading.value = true;
    try {
      const res = await fetchApi({
        page: currentPage.value,
        pageSize: pageSize.value,
        ...searchParams.value,
        ...extraParams
      });
      tableData.value = res.data.list;
      total.value = res.data.total;
    } catch (error) {
      console.error('获取数据失败', error);
      tableData.value = [];
      total.value = 0;
    } finally {
      loading.value = false;
    }
  };

  // 刷新数据（保持当前分页和搜索条件）
  const refresh = () => {
    fetchData();
  };

  // 重置到第一页并刷新
  const resetAndRefresh = () => {
    currentPage.value = 1;
    searchParams.value = {};
    fetchData();
  };

  // 立即加载数据
  if (immediate) {
    onMounted(() => {
      fetchData();
    });
  }

  return {
    // 数据
    tableData,
    loading,
    currentPage,
    pageSize,
    total,
    searchItems,
    tableColumns,
    searchParams,

    // 方法
    handleSearch,
    handleReset,
    handlePageChange,
    fetchData,
    refresh,
    resetAndRefresh
  };
}
